﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DTTB.MV2.QUANLYNHANSUTIENLUONG.Models.LinQ.ChamCong;
using DTTB.MV2.QUANLYNHANSUTIENLUONG.Models.FormBean.NhanVienModel;
using System.Web.Mvc;

namespace DTTB.MV2.QUANLYNHANSUTIENLUONG.BussinessDelegate.NhanVienDelegate
{
    public class TamUngDelegate
    {
        #region Private Member

        CommonDelegate.CommonDelegate commonDelegate = new CommonDelegate.CommonDelegate();
        ChamCongDelegate.ChamCongServiceDelegate chamCongServiceDelegate = new ChamCongDelegate.ChamCongServiceDelegate();
        DBChamCongDataContext dBChamCong = new DBChamCongDataContext();
        readonly int _currentUserId = Convert.ToInt32(HttpContext.Current.Session["USERID"].ToString());

        #endregion

        #region Get

        #region Bảng tb_TamUng

        private IQueryable<tb_TamUng> QueryGetAllTamUng()
        {
            return dBChamCong.tb_TamUngs;
        }

        private IQueryable<tb_TamUng> QueryGetAllTamUngByThangNam(int thang, int nam)
        {
            return dBChamCong.tb_TamUngs.Where(p =>  p.NamTamUng == nam && p.ThangTamUng == thang && (p.IsDelete == false || p.IsDelete == null));
        }

        public IList<tb_TamUng> GetAllTamUng()
        {
            return dBChamCong.tb_TamUngs.Where(p => p.IsDelete == false || p.IsDelete == null).ToList();
        }

        public IList<tb_TamUng> GetAllTamUngOrderByDescendingNgayTamUng()
        {
            return dBChamCong.tb_TamUngs.Where(p => p.IsDelete == false || p.IsDelete == null).OrderByDescending(p => p.NgayTamUng).ToList();
        }

        public tb_TamUng GetTamUngById(int? id)
        {
            return dBChamCong.tb_TamUngs.SingleOrDefault(p => p.ID == id);
        }

        public tb_TamUng GetTamUngById(string id)
        {
            try
            {
                return GetTamUngById(Convert.ToInt32(id));
            }
            catch (Exception)
            {
                return null;
            }
        }

        public IList<tb_TamUng> SearchTamUngByThangNamOrderByTen(int thang, int nam, int? idPhongBan, int? idChucVu, string hoTen, int pageIndex, int itemPerPage, ref int totalItem, ref int totalPage)
        {
            try
            {
                hoTen = !string.IsNullOrEmpty(hoTen) ? hoTen.Trim() : string.Empty;
                pageIndex = pageIndex > 1 ? pageIndex : 1;
                totalItem = 0;
                totalPage = 0;

                if (idPhongBan > 0 && idChucVu > 0)
                {
                    #region Tìm theo Phòng Ban && Chức Vụ
                    if (!string.IsNullOrEmpty(hoTen))
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdPhongBan == idPhongBan
                                        && nviennew.IdChucVu == idChucVu
                                        && ((nviennew.Ho.Trim() + " " + nviennew.Ten.Trim()).Contains(hoTen) || nviennew.SoThe.Contains(hoTen))
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    else
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.ID equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdPhongBan == idPhongBan
                                        && nviennew.IdChucVu == idChucVu
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    #endregion
                }
                if (idPhongBan > 0)
                {
                    #region Tìm theo Phòng Ban
                    if (!string.IsNullOrEmpty(hoTen))
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdPhongBan == idPhongBan
                                        && ((nviennew.Ho.Trim() + " " + nviennew.Ten.Trim()).Contains(hoTen) || nviennew.SoThe.Contains(hoTen))
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    else
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdPhongBan == idPhongBan
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    #endregion
                }
                if (idChucVu > 0)
                {
                    #region Tìm theo Chức Vụ
                    if (!string.IsNullOrEmpty(hoTen))
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdChucVu == idChucVu
                                        && ((nviennew.Ho.Trim() + " " + nviennew.Ten.Trim()).Contains(hoTen) || nviennew.SoThe.Contains(hoTen))
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    else
                    {
                        var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                    join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                    into t
                                    from nviennew in t.DefaultIfEmpty()
                                    where
                                        nviennew.IdChucVu == idChucVu
                                    orderby nviennew.Ten.Trim()
                                    select tamung;

                        totalItem = query.Count();
                        if (itemPerPage > 0)
                        {
                            if (totalItem % itemPerPage == 0)
                                totalPage = totalItem / itemPerPage;
                            else
                                totalPage = (totalItem / itemPerPage) + 1;

                            return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                        }
                        totalPage = totalItem > 0 ? 1 : 0;
                        return query.ToList();
                    }
                    #endregion
                }

                if (!string.IsNullOrEmpty(hoTen))
                {
                    var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                into t
                                from nviennew in t.DefaultIfEmpty()
                                where
                                    ((nviennew.Ho.Trim() + " " + nviennew.Ten.Trim()).Contains(hoTen) || nviennew.SoThe.Contains(hoTen))
                                orderby nviennew.Ten.Trim()
                                select tamung;

                    totalItem = query.Count();
                    if (itemPerPage > 0)
                    {
                        if (totalItem % itemPerPage == 0)
                            totalPage = totalItem / itemPerPage;
                        else
                            totalPage = (totalItem / itemPerPage) + 1;

                        return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                    }
                    totalPage = totalItem > 0 ? 1 : 0;
                    return query.ToList();
                }
                else
                {
                    var query = from tamung in QueryGetAllTamUngByThangNam(thang, nam)
                                join nvien in dBChamCong.hs_NhanViens on tamung.IdNhanVien equals nvien.Id
                                into t
                                from nviennew in t.DefaultIfEmpty()
                                orderby nviennew.Ten.Trim()
                                select tamung;

                    totalItem = query.Count();
                    if (itemPerPage > 0)
                    {
                        if (totalItem % itemPerPage == 0)
                            totalPage = totalItem / itemPerPage;
                        else
                            totalPage = (totalItem / itemPerPage) + 1;

                        return query.Skip((pageIndex - 1) * itemPerPage).Take(itemPerPage).ToList();
                    }
                    totalPage = totalItem > 0 ? 1 : 0;
                    return query.ToList();
                }
            }
            catch (Exception)
            {
                return new List<tb_TamUng>();
            }
        }

        public IQueryable<int> QueryGetIdNhanVienCoTrongTamUng(int thang, int nam)
        {
            return QueryGetAllTamUngByThangNam(thang, nam).Select(p => p.IdNhanVien);
        }

        public IQueryable<int> QueryGetIdNhanVienKhongCoTrongTamUng(int thang, int nam)
        {
            return QueryGetAllNhanVien().Where(p => !QueryGetIdNhanVienCoTrongTamUng(thang, nam).Contains(p.Id)).Select(p => p.Id);
        }

        public bool IsExistsTamUng(int idNhanVien, int thang, int nam)
        {
            if (dBChamCong.tb_TamUngs
                    .SingleOrDefault(p =>
                        p.ThangTamUng == thang && p.NamTamUng == nam
                        && p.IdNhanVien == idNhanVien && (p.IsDelete == false || p.IsDelete == null)) != null)
                return true;
            return false;
        }

        public bool IsAllowEdit(int idTamUng)
        {
            var objTamUng = GetTamUngById(idTamUng);

            if (objTamUng != null)
            {
                return IsAllowEdit(objTamUng.ThangTamUng, objTamUng.NamTamUng);
            }

            return false;
        }

        public bool IsAllowEdit(int thang, int nam)
        {
            var objBangLuong = GetDanhSachBangTinhLuongByThangNam(thang, nam);
            if (objBangLuong != null)
            {
                if (!objBangLuong.IsFinish)
                    return true;
            }
            else
                return true;    //Bảng Lương không có, nên có thể Chỉnh Sửa Tạm Ứng (Thêm/Xóa/Sửa)
            return false;
        }

        #endregion

        #region Bảng tb_NhanVien

        public IQueryable<hs_NhanVien> QueryGetAllNhanVien()
        {
            return dBChamCong.hs_NhanViens.Where(p => p.IsDelete == false || p.IsDelete == null);
        }

        public hs_NhanVien GetNhanVienById(int? idNhanVien)
        {
            return dBChamCong.hs_NhanViens.SingleOrDefault(p => p.Id == idNhanVien);
        }

        #endregion

        #region Bảng tb

        public tb_DanhSachBangTinhLuong GetDanhSachBangTinhLuongByThangNam(int thang, int nam)
        {
            return dBChamCong.tb_DanhSachBangTinhLuongs.SingleOrDefault(p => p.Thang == thang & p.Nam == nam);
        }

        #endregion

        #endregion

        #region Set

        public tb_TamUng AddTamUng(tb_TamUng objTamUng)
        {
            try
            {
                objTamUng.NguoiTao = _currentUserId;
                objTamUng.NgayTao = DateTime.Now;
                objTamUng.NguoiSua = _currentUserId;
                objTamUng.NgaySua = DateTime.Now;
                objTamUng.IsDelete = false;
                dBChamCong.tb_TamUngs.InsertOnSubmit(objTamUng);
                dBChamCong.SubmitChanges();
                return objTamUng;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public tb_TamUng UpdateTamUng(tb_TamUng objTamUng)
        {
            try
            {
                objTamUng.NguoiSua = _currentUserId;
                objTamUng.NgaySua = DateTime.Now;
                dBChamCong.SubmitChanges();
                return objTamUng;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool DeleteTamUng(tb_TamUng objTamUng)
        {
            try
            {
                objTamUng.IsDelete = true;
                objTamUng.NguoiSua = _currentUserId;
                objTamUng.NgaySua = DateTime.Now;
                dBChamCong.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool DeleteTamUng(int? idTamUng)
        {
            tb_TamUng objTamUng = GetTamUngById(idTamUng);
            return DeleteTamUng(objTamUng);
        }

        public bool DeleteTamUng(string idTamUng)
        {
            tb_TamUng objTamUng = GetTamUngById(idTamUng);
            return DeleteTamUng(objTamUng);
        }

        public bool ShiftDeleteTamUng(tb_TamUng objTamUng)
        {
            try
            {
                dBChamCong.tb_TamUngs.DeleteOnSubmit(objTamUng);
                dBChamCong.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool ShiftDeleteTamUng(int? idTamUng)
        {
            tb_TamUng objTamUng = GetTamUngById(idTamUng);
            return ShiftDeleteTamUng(objTamUng);
        }

        public bool ShiftDeleteTamUng(string idTamUng)
        {
            tb_TamUng objTamUng = GetTamUngById(idTamUng);
            return ShiftDeleteTamUng(objTamUng);
        }

        #endregion

        #region Build

        public TamUngForm BuildTamUngForm(tb_TamUng objTamUng)
        {
            var form = new TamUngForm();
            form.Id = objTamUng.ID;
            form.NgayTamUng = commonDelegate.ConvertDateTimeToString(objTamUng.NgayTamUng);
            form.ThangTamUng = objTamUng.ThangTamUng;
            form.NamTamUng = objTamUng.NamTamUng;
            form.SoTien = objTamUng.SoTien.ToString("#,0");
            form.LyDo = objTamUng.LyDo;
            form.GhiChu = objTamUng.GhiChu;
            form.NguoiTao = objTamUng.NguoiTao;
            form.NgayTao = commonDelegate.ConvertDateTimeToString(objTamUng.NgayTao);
            form.NguoiSua = objTamUng.NguoiSua;
            form.NgaySua = commonDelegate.ConvertDateTimeToString(objTamUng.NgaySua);
            form.IsDelete = objTamUng.IsDelete ?? false;

            form.HoTenNguoiTao = commonDelegate.GetDisplayNameByUserId(Convert.ToString(objTamUng.NguoiTao));
            form.HoTenNguoiSua = commonDelegate.GetDisplayNameByUserId(Convert.ToString(objTamUng.NguoiSua));

            var objNhanVien = GetNhanVienById(objTamUng.IdNhanVien);
            if (objNhanVien != null)
            {
                form.IdNhanVien = objTamUng.IdNhanVien;
                form.SoThe = objNhanVien.SoThe;
                form.HoTen = chamCongServiceDelegate.GhepHoVaTen(objNhanVien.Ho, objNhanVien.Ten);
            }
            return form;
        }

        public TamUngForm BuildTamUngForm(tb_TamUng objTamUng, hs_NhanVien objNhanVien)
        {
            var form = new TamUngForm();
            form.Id = objTamUng.ID;
            form.NgayTamUng = commonDelegate.ConvertDateTimeToString(objTamUng.NgayTamUng);
            form.ThangTamUng = objTamUng.ThangTamUng;
            form.NamTamUng = objTamUng.NamTamUng;
            form.SoTien = objTamUng.SoTien.ToString("#,0");
            form.LyDo = objTamUng.LyDo;
            form.GhiChu = objTamUng.GhiChu;
            form.NguoiTao = objTamUng.NguoiTao;
            form.NgayTao = commonDelegate.ConvertDateTimeToString(objTamUng.NgayTao);
            form.NguoiSua = objTamUng.NguoiSua;
            form.NgaySua = commonDelegate.ConvertDateTimeToString(objTamUng.NgaySua);
            form.IsDelete = objTamUng.IsDelete ?? false;

            form.HoTenNguoiTao = commonDelegate.GetDisplayNameByUserId(Convert.ToString(objTamUng.NguoiTao));
            form.HoTenNguoiSua = commonDelegate.GetDisplayNameByUserId(Convert.ToString(objTamUng.NguoiSua));

            form.IdNhanVien = objTamUng.IdNhanVien;
            form.SoThe = objNhanVien.SoThe;
            form.HoTen = chamCongServiceDelegate.GhepHoVaTen(objNhanVien.Ho, objNhanVien.Ten);
            return form;
        }

        public tb_TamUng BuildTamUngLinQ(TamUngForm form)
        {
            var obj = new tb_TamUng();
            if (form.Id > 0)
            {
                obj = GetTamUngById(form.Id);
            }
            obj.NgayTamUng = commonDelegate.ConvertStringToDateTime(form.NgayTamUng.Trim()).Value;
            obj.ThangTamUng = (byte)form.ThangTamUng;
            obj.NamTamUng = (short)form.NamTamUng;
            obj.SoTien = commonDelegate.ConvertStringToDecimal(form.SoTien);
            obj.LyDo = !string.IsNullOrEmpty(form.LyDo)
                            ? form.LyDo.Trim()
                            : string.Empty;
            obj.GhiChu = !string.IsNullOrEmpty(form.GhiChu)
                             ? form.GhiChu.Trim()
                             : string.Empty;
            return obj;
        }

        /// <summary>
        /// Build Danh Sách Tạm Ứng theo Tháng/Năm. Sắp xếp theo Tên
        /// </summary>
        /// <param name="form"></param>
        public void BuildDanhSachTamUngTheoThang(TamUngForm form)
        {
            var totalItem = 0;
            var totalPage = 0;
            //Lấy tất cả nhân viên trong bảng Tạm Ứng (Phân trang)
            //Tìm Kiếm nhân viên trong bảng Tạm Ứng
            var lstTamUng = SearchTamUngByThangNamOrderByTen(
                                        form.ThangTamUng, form.NamTamUng, form.SearchByIdPhongBan, form.SearchByIdChucVu, form.SearchByHoTen,
                                        form.PageIndex, form.ItemPerPage, ref totalItem, ref totalPage);
            form.TotalItem = totalItem;
            form.TotalPage = totalPage;

            foreach (var itemTamUng in lstTamUng)
            {
                form.ListTamUng.Add(BuildTamUngForm(itemTamUng));
            }
        }

        /// <summary>
        /// Build Select List Nhân viên có trong Bảng Tạm Ứng
        /// </summary>
        /// <param name="thang">Tháng Tạm Ứng</param>
        /// <param name="nam">Năm Tạm Ứng</param>
        /// <returns></returns>
        public SelectList BuildSelectListNhanVienCoTrongTamUng(int thang, int nam)
        {
            var listIdNhanVienCoTrongBangTamUng = QueryGetIdNhanVienCoTrongTamUng(thang, nam).ToList();

            IList<object> selectList = new List<object> { new { Value = 0, Text = "[-- Chọn Nhân Viên --]" } };

            foreach (var itemIdNhanVien in listIdNhanVienCoTrongBangTamUng)
            {
                var objNhanVien = GetNhanVienById(itemIdNhanVien);
                selectList.Add(new { Value = itemIdNhanVien, Text = "(" + objNhanVien.SoThe + ") " + chamCongServiceDelegate.GhepHoVaTen(objNhanVien.Ho, objNhanVien.Ten)  });
            }

            return new SelectList(selectList, "Value", "Text");
        }

        /// <summary>
        /// Build Select List Nhân viên KHÔNG có trong Bảng Tạm Ứng
        /// </summary>
        /// <param name="thang">Tháng Tạm Ứng</param>
        /// <param name="nam">Năm Tạm Ứng</param>
        /// <returns></returns>
        public SelectList BuildSelectListNhanVienKhongCoTrongTamUng(int thang, int nam)
        {
            var listIdNhanVienKhongCoTrongBangTamUng = QueryGetIdNhanVienKhongCoTrongTamUng(thang, nam).ToList();

            IList<object> selectList = new List<object> { new { Value = 0, Text = "[-- Chọn Nhân Viên --]" } };

            foreach (var itemIdNhanVien in listIdNhanVienKhongCoTrongBangTamUng)
            {
                var objNhanVien = GetNhanVienById(itemIdNhanVien);
                selectList.Add(new { Value = itemIdNhanVien, Text = "(" + objNhanVien.SoThe + ") " + chamCongServiceDelegate.GhepHoVaTen(objNhanVien.Ho, objNhanVien.Ten) });
            }

            return new SelectList(selectList, "Value", "Text");
        }

        /// <summary>
        /// Build Select List Tất cả Nhân viên
        /// </summary>
        /// <returns></returns>
        public SelectList BuildSelectListNhanVien()
        {
            var listIdNhanVien = QueryGetAllNhanVien().Select(p => p.Id).ToList();

            IList<object> selectList = new List<object> { new { Value = 0, Text = "[-- Chọn Nhân Viên --]" } };

            foreach (var itemIdNhanVien in listIdNhanVien)
            {
                var objNhanVien = GetNhanVienById(itemIdNhanVien);
                selectList.Add(new { Value = itemIdNhanVien, Text = "(" + objNhanVien.SoThe + ") " + chamCongServiceDelegate.GhepHoVaTen(objNhanVien.Ho, objNhanVien.Ten) });
            }

            return new SelectList(selectList, "Value", "Text");
        }
        #endregion
    }
}